package com.example.wnn;

import cn.hutool.json.JSONUtil;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricActivityInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;


import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@SpringBootTest
public class ActicvitiTest2 {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private IdentityService identityService;



    /**
     * 手动部署
     */
    @Test
    public void deployment(){
        DeploymentBuilder deployment = repositoryService.createDeployment();
        Deployment deploy = deployment.name("demo")
                .addClasspathResource("processes/demo.bpmn20.xml")
                .deploy();
        System.out.println("部署ID："+deploy.getId());
        System.out.println("部署名称："+deploy.getName());

        //listDeployments();
    }


    /**
     * 查询流程部署列表
     */
    @Test
    public void init() {
        List<Deployment> deployments = this.repositoryService.createDeploymentQuery().list();
        if (!deployments.isEmpty()) {
            deployments.forEach(deployment -> {
                System.out.println(">>>-----");
                System.out.println("Id：" + deployment.getId());
                System.out.println("Name：" + deployment.getName());
                System.out.println("DeploymentTime：" + deployment.getDeploymentTime());
                System.out.println("Key：" + deployment.getKey());
                System.out.println(">>>-----");
                repositoryService.deleteDeployment(deployment.getId(),true);


            });
        }
        deployment();
        startProcess();
    }


    /**
     * 删除流程部署
     */
    @Test
    public void deleteDeplyoment(){
        //第二个参数为级联删除，默认为false(有该流程的实例则不能删除),设置true则为级联删除
        repositoryService.deleteDeployment("97501",true);
    }


    /**
     * 启动一个流程实例
     */
    @Test
    public void startProcess(){
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .processDefinitionKey("demo")
                .singleResult();
        System.out.println(processDefinition.getId());

        String businessKey = "ywID:22222";
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(),businessKey);

        System.out.println("流程定义id：" + processInstance.getProcessDefinitionId());
        System.out.println("流程实例id：" + processInstance.getId());
        System.out.println("当前活动id：" + processInstance.getActivityId());
        System.out.println("业务id:"+processInstance.getBusinessKey());

    }

    @Test
    public void selectProcessInstance(){
        String businessKey = "ywID:22222";

        ProcessInstanceQuery processInstanceQuery = runtimeService.createProcessInstanceQuery();
        ProcessInstance processInstance=  processInstanceQuery
                .processInstanceBusinessKey(businessKey).singleResult();

        System.out.println(processInstance.getProcessInstanceId());

    }


    /**
     * 查询任务列表
     */
    @Test
   public void job(){
        TaskQuery taskQuery = taskService.createTaskQuery();
        String userId = "100";
        List<Task> task = taskQuery
                //.processDefinitionKey("demo")//流程实例key
              // .taskCandidateGroupIn(Arrays.asList("financeManage","chiefEngineer","teamsGroups"))
               // .taskAssignee("101")
                .taskCandidateUser(userId)
              //  .processInstanceBusinessKey("99999")
                .list();

        if (!CollectionUtils.isEmpty(task)){
            for (Task item : task) {
                System.out.println(JSONUtil.parse(task));
                System.out.println("任务id:"+item.getId());
                System.out.println("任务名称:"+item.getName());
                System.out.println("任务负责人:"+item.getAssignee());
                System.out.println("流程定义id:"+item.getProcessDefinitionId());
                System.out.println("流程实例id:"+item.getProcessInstanceId());
                System.out.println("任务创建时间:"+item.getCreateTime());

                ProcessInstanceQuery processInstanceQuery =  runtimeService.createProcessInstanceQuery();
                processInstanceQuery.processInstanceId(item.getProcessInstanceId());
                ProcessInstance processInstance = processInstanceQuery.singleResult();
                //找到业务ID  这个做测试是要用单个，实际一应该用集合 todo
                System.out.println("业务ID ："+processInstance.getBusinessKey());

                System.out.println("");
                System.out.println("");
                taskService.claim(item.getId(),userId);
                taskService.addComment(item.getId(),processInstance.getProcessInstanceId(),"测试审核通过");
                taskService.complete(item.getId());


            }
        }else {
            System.out.println("未获取到任务数据");

        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
   //     job();


    }

    /**
     * 根据流程的key和任务负责人 处理任务
     */
    @Test
    public void solveTask() {

        Task task = taskService.createTaskQuery().processDefinitionKey("demo").taskAssignee("100").singleResult();
        System.out.println("任务id:"+task.getId());
        System.out.println("任务名称:"+task.getName());
        System.out.println("任务负责人:"+task.getAssignee());

        taskService.complete(task.getId());   //搞懂这个 complete

        System.out.println("任务处理完毕");




    }
    /**
     * 拾取任务
     */
    @Test
    public void claimTask() {
        //获取ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //获取TaskService对象
        TaskService taskService = processEngine.getTaskService();
        //获取组任务
        String candidateUser="101";
        Task task = taskService.createTaskQuery().processDefinitionKey("demo").taskCandidateUser(candidateUser).singleResult();
        //不等于Null代表能够获取到该任务
        if(task!=null){
            //拾取任务   任务ID，任务执行人
            taskService.claim(task.getId(),candidateUser);
            System.out.println("任务被："+candidateUser+"拾取~");
        }
    }



    @Test
    public void dele() {
         //交办任务
        taskService.setAssignee("1d70aea7-4096-11ee-81ab-aaab435140fa","wenzheng");
    }



    //用户的个人处理历史 todo

    //退回

    /**
     * 查看任务
     */
    @Test
    public void getTask() {
        //获取ProcessEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //获取TaskService对象
        TaskService taskService = processEngine.getTaskService();
        //查询到自己的任务，然后通过任务ID进行提交
        Task task = taskService.createTaskQuery().processDefinitionKey("demo").taskAssignee("101").singleResult();
        //处理任务
        if(task!=null){
            taskService.complete(task.getId());
            System.out.println("任务处理完毕");
        }
    }

    /**
     * 流程历史信息查看
     * 即时删除了流程，但是流程的历史信息还是会被保存下来，存在hi**表中
     * 也可以不加过滤条件，查询出全部
     */
     @Test
    public void searchHistoricActivityInstance() {
        String id = "contract001:1:a71a31fc-3be7-11ee-86f3-aaab435140fa";
        //获取actinst表的查询对象
        HistoricActivityInstanceQuery historicActivityInstanceQuery = historyService.createHistoricActivityInstanceQuery();
        //查询actinst表，根据流程id查询
        HistoricActivityInstanceQuery historicActivityInstanceQuery1 = historicActivityInstanceQuery.processDefinitionId(id);
        //查询actinst表，根据流程实例id查询
        //historicActivityInstanceQuery.processInstanceId(流程实例id);
        //排序
        historicActivityInstanceQuery1.orderByHistoricActivityInstanceStartTime().desc();
        //获取查询结果
        List<HistoricActivityInstance> list = historicActivityInstanceQuery1.list();
        //输出查询结果
        for (HistoricActivityInstance hi : list) {
            System.out.println(hi.getActivityId());
            System.out.println(hi.getActivityName());
            System.out.println(hi.getActivityType());
            System.out.println(hi.getAssignee());
            System.out.println(hi.getProcessDefinitionId());
            System.out.println(hi.getProcessInstanceId());
        }
    }

    @Test
    public Group saveGroup(String groupId, String name) {
        Group g = identityService.newGroup(groupId);
        g.setName(name);
        identityService.saveGroup(g);
        return g;
    }

    @Test
    public User saveUser(String userId,String name) {
        User u = identityService.newUser(userId);
        u.setFirstName(name);
        u.setPassword("111111");
        identityService.saveUser(u);
        return u;
    }

    @Test
    public void saveRel(User u, Group g) {
        identityService.createMembership(u.getId(), g.getId());
    }

    @Test
    public void del() {
        identityService.deleteMembership("100","teamsGroups");
    }

    @Test
    public void userIntoWorkerServer(){
         User user = saveUser("100","文峥");
         User user1 = saveUser("101","张三");
        User user2 = saveUser("102","李四");
        User user3 = saveUser("103","王五");

        Group group1 =   saveGroup("financeManage","财务");
         Group group2 =   saveGroup("chiefEngineer","工程师");
        Group group3 =   saveGroup("teamsGroups","班组");

        saveRel(user,group1);
        saveRel(user,group2);
        saveRel(user,group3);

        saveRel(user1,group1);
        saveRel(user2,group2);
        saveRel(user3,group3);



    }



    /*** 根据办理人查询任务*/@Test
    public void queryHisTaskByAssignee(){
        String assignee = "100";


        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(assignee)
                .list();

        for (HistoricTaskInstance historicTaskInstance : list) {
            System.out.println("任务id: "+historicTaskInstance.getId());
            System.out.println("任务名字: "+historicTaskInstance.getName());
            System.out.println("任务创建时间: "+historicTaskInstance.getEndTime());
            System.out.println("办理人: "+historicTaskInstance.getAssignee());
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");

           List<Comment> comments =  taskService.getTaskComments(historicTaskInstance.getId());
            for (Comment comment : comments) {
                System.out.println(comment.getFullMessage());

            }

        }
    }



   /* *//**    ---------- 业务代码测试  -----------*//*
    @Autowired
    private WorkflowService workflowService;

    @Test
    public void test() {
        workflowService.generateDeployBpmn("qwewewqe-qweqw-12",
                Arrays.asList("financeManage","chiefEngineer","teamsGroups"));



    }*/

    /**
     * 查询流程状态（正在执行 or 已经执行结束）
     */
    @Test
    public void processState(){
        ProcessInstance pi=runtimeService// 获取运行时Service
                .createProcessInstanceQuery() // 创建流程实例查询
                .processInstanceId("140001") // 用流程实例ID查询
                .singleResult();
        if(pi!=null){
            System.out.println("流程正在执行！");
        }else{
            System.out.println("流程已经执行结束！");
        }
    }

}
